<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/3/21
 * Time: 10:09
 * 发现
 */
namespace app\api\controller;
use think\Db;
class Find extends Base {

    /**
     * 发现类型
     * @return \think\response\Json
     */
    public function assortment(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == 112) {
            return json(['status' => 301, 'msg' => $this->otherLogin]);
        }elseif($res == 110){
            return json(['status' => 302, 'msg' => $this->frost]);
        }
        if(isset($params['old_1']) && $params['old_1'] == 1){ //特别照顾旧版本
            $res = Db::name('notice_assortment')->where('assortment_id',2)->select();
        }else{
            $res = Db::name('notice_assortment')->order('assortment_sort asc')->select();
        }
        return  json(array('status'=>200,'msg'=>$res));
    }

    /**
     * 发现列表
     * @return \think\response\Json
     * assortment_id  类型ID   0 全部  1 研学活动  2 缴费通知  3 家庭教育  4 校园新闻
     *                         5 美文赏析  6 图书推荐
     */
    public function findList(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == 112) {
            return json(['status' => 301, 'msg' => $this->otherLogin]);
        }elseif($res == 110){
            return json(['status' => 302, 'msg' => $this->frost]);
        }
        
        $page = input('param.page')?input('param.page'):1;
        $assortment_id = input('assortment_id');
        $where = [];
        $user_info = Db::table('up_u_user')->where('user_id', $params['user_id'])->find();
        $school_id_str = ',' . $user_info['user_school'] . ',';
//        $qu_id_str = ',' . $user_info['user_qu'] . ',';
        if($assortment_id == 0){ //全部
            $where['n_school'] = ['like', '%' . $school_id_str . '%'];
        }else if($assortment_id == 1){//研学
            $where['n_type'] = $assortment_id;
            $where['n_school'] = ['like', '%' . $school_id_str . '%'];
        }else{//缴费通知、家庭教育、校园新闻、美文赏析、图书推荐
            $where['n_type'] = $assortment_id;
            $where['n_school'] = ['like', '%' . $school_id_str . '%'];
        }
        $where['n_status'] = 1;
        $where['n_del'] = 1;

        $findLists = Db::table('up_notice')
            ->field('n_id, n_title, n_type, n_time, n_thumb, n_start_time, n_end_time, n_apply_start_time, 
            n_apply_end_time')
            ->where($where)
            ->page($page, 10)
            ->order('n_time desc')
            ->select();
        foreach ($findLists as $key=>&$vo){
            $vo['n_time'] = date('Y.m.d H:i:s',strtotime($vo['n_time']));
        }
        if($findLists){
            if($assortment_id == 0 || $assortment_id == 1){//全部、研学要显示是否已报名
                $findLists = $this->getFindLists($params['user_id'], $findLists);
            }
            return json(['status' => 200, 'msg' => $findLists]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    /**
     * 发现列表
     * @return \think\response\Json
     * assortment_id  类型ID   0 全部  1 研学活动  2 缴费通知  3 家庭教育  4 校园新闻
     *                         5 美文赏析  6 图书推荐
     */
    public function UserFindList(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == 112) {
            return json(['status' => 301, 'msg' => $this->otherLogin]);
        }elseif($res == 110){
            return json(['status' => 302, 'msg' => $this->frost]);
        }

        $page = input('param.page')?input('param.page'):1;
        $where = [];

        $where['a.st_user_id'] = $params['user_id'];
        $where['a.st_pay_status'] = 2;
//        $findLists = Db::table('up_notice')
//            ->field('n_id, n_title, n_type, n_time, n_thumb, n_start_time, n_end_time, n_apply_start_time,
//            n_apply_end_time')
//            ->where($where)
//            ->page($page, 10)
//            ->order('n_time desc')
//            ->select();
        $findLists = Db::table('up_studies')->alias('a')
            ->join('up_notice un','un.n_id = a.st_n_id','left')
            ->where($where)
            ->page($page, 10)
            ->field('un.n_id, un.n_title, un.n_type, un.n_time, un.n_thumb, un.n_start_time, un.n_end_time, un.n_apply_start_time, 
           un.n_apply_end_time,st_time')
            ->order('st_time desc')
            ->select();
        foreach ($findLists as $key=>&$vo){
            $vo['n_time'] = date('Y.m.d H:i:s',strtotime($vo['st_time']));
        }
        if($findLists){
            return json(['status' => 200, 'msg' => $findLists]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    /**
     * 发现详情
     * @return \think\response\Json
     * n_id  发现消息的ID
     * page  用于研学活动报名用户列表的分页
     */
    public function findDetail(){
        header('Access-Control-Allow-Origin:*');
        $params = input('param.');
        if(!isset($params['is_share'])){
            $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
            if($res == 112) {
                return json(['status' => 301, 'msg' => $this->otherLogin]);
            }elseif($res == 110){
                return json(['status' => 302, 'msg' => $this->frost]);
            }
        }
        
        $field = 'n_id, n_type, n_title, n_thumb, n_content, n_time, n_start_time, n_end_time, 
        n_apply_start_time, n_apply_end_time, n_money, n_num, n_num_already, n_linkman, 
        n_phone, n_link, n_img';
        
        $noticeInfo = Db::table('up_notice')
            ->field($field)
            ->where('n_id', $params['n_id'])
            ->find();
        
        if($noticeInfo){
            if($noticeInfo['n_type'] == 1){//研学管理
                //已报名
                $apply = Db::table('up_studies')
                    ->where('st_n_id', $noticeInfo['n_id'])
                    ->where('st_user_id', $params['user_id'])
                    ->find();
                if($apply && $apply['st_pay_status'] == 2){//已缴费
                    $noticeInfo['apply'] = 1;//已报名
                }else{
                    $noticeInfo['apply'] = 0;//未报名
                }
                
                //已结束
                if(time() > strtotime($noticeInfo['n_end_time'])){
                    $noticeInfo['end'] = 1;//已结束
                }else{
                    $noticeInfo['end'] = 0;
                }
    
                //时间格式
                $noticeInfo['n_start_time'] = date('Y.m.d', strtotime($noticeInfo['n_start_time']));
                $noticeInfo['n_end_time'] = date('Y.m.d', strtotime($noticeInfo['n_end_time']));
                $noticeInfo['n_apply_start_time'] = date('Y.m.d H:i:s', strtotime($noticeInfo['n_apply_start_time']));
                $noticeInfo['n_apply_end_time'] = date('Y.m.d H:i:s', strtotime($noticeInfo['n_apply_end_time']));

                //已报名用户
//                $page = input('page') ? input('page') : 1;
                $applyed = Db::table('up_studies')
                    ->join('up_u_user', 'st_user_id = user_id', 'left')
                    ->field('user_username, user_image, st_user_name')
                    ->where('st_n_id', $noticeInfo['n_id'])
                    ->where('st_pay_status', 2)
//                    ->page($page, 10)
                    ->select();
                $where1['n_id'] = $params['n_id'];
                $where1['notice_user_id'] = $params['user_id'];
                $all = Db::table('up_notice_order')->where($where1)->find();

                $where2['st_n_id'] = $params['n_id'];
                $where2['st_user_id'] = $params['user_id'];
                $all2 = Db::table('up_studies')->where($where2)->find();
                $noticeInfo['applyed'] = $applyed;
                $noticeInfo['notice_id'] = $all['notice_id'];
                $noticeInfo['st_id'] = $all2['st_id'];
            }else{
                $noticeInfo['notice_id'] = '';
                $noticeInfo['st_id'] = '';
            }
            $noticeInfo['n_time'] = date('Y.m.d H:i:s', strtotime($noticeInfo['n_time']));

            //阅读量+1
            Db::table('up_notice')->where('n_id', $params['n_id'])->setInc('n_quantity');
            
            return json(['status' => 200, 'msg' => $noticeInfo]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 消息报名
     * @return \think\response\Json
     * n_id             消息ID
     * st_user_phone    紧急联系手机
     * st_urg_name      紧急联系人姓名
     * st_user_code     报名研学活动的用户身份证号
     * st_user_name     报名研学活动的用户姓名
     */
    public function apply(){
        $params = input('param.');
        $where1['n_id'] = $params['n_id'];
        $where1['notice_user_id'] = $params['user_id'];
        $rr = Db::table('up_notice_order')->where($where1)->find();
        if($rr['notice_id']!=''){
            return json(['status' => 200, 'msg' => $rr['notice_id']]);
        }
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == 112) {
            return json(['status' => 301, 'msg' => $this->otherLogin]);
        }elseif($res == 110){
            return json(['status' => 302, 'msg' => $this->frost]);
        }
        $isHave = Db::table('up_studies')
            ->where('st_n_id', $params['n_id'])
            ->where('st_user_code', $params['st_user_code'])
            ->find();
        if($isHave) return json(['status' => 202, 'msg' => '该用户已报名该活动']);
        $noticeInfo = Db::table('up_notice')->where('n_id', $params['n_id'])->find();
        //先判断报名人数和实际缴费人数是否相同，如果实际缴费人数小于已报名人数，则将已报名人数改为实际缴费人数
//        $num = Db::table('up_studies')->where('st_n_id', $params['n_id'])->count();
//        if($num < $noticeInfo['n_num_already']){
//            Db::table('up_notice')->where('n_id', $params['n_id'])->setField('n_num_already', $num);
//        }

        if(time() < strtotime($noticeInfo['n_apply_start_time']) || time() > strtotime($noticeInfo['n_apply_end_time'])){
            return json(['status' => 0, 'msg' => '不在报名时间内']);
        }
        
        if($noticeInfo['n_num'] <= $noticeInfo['n_num_already']){
            return json(['status' => 0, 'msg' => '报名人数已满']);
        }
        $data['st_n_id'] = $params['n_id'];
        $data['st_user_id'] = $params['user_id'];
        $data['st_time'] = date('Y-m-d H:i:s',time());
        $data['st_money'] = $noticeInfo['n_money'];
        $data['st_user_name'] = $params['st_user_name'];
        $data['st_user_code'] = $params['st_user_code'];
        $data['st_user_phone'] = $params['st_user_phone'];
        $data['st_urg_name'] = $params['st_urg_name'];
        //插入报名表
        $res1 = Db::table('up_studies')->insertGetId($data);
        //需要写到付款成功的回调里面
        //插入研学活动订单表
        $order_number = date('YmdHis') . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);//订单编号
        $dataAll['notice_num'] = $order_number;
        $dataAll['notice_user_id'] =$params['user_id'];
        $dataAll['notice_time'] = date('Y-m-d H:i:s',time());
        $dataAll['n_id'] = $params['n_id'];
        $dataAll['notice_money'] = $noticeInfo['n_money'];
        $dataAll['studies_id'] = $res1;
        $res2 = Db::table('up_notice_order')->insertGetId($dataAll);
        if($res1){
            return json(['status' => 200, 'msg' => $res2]);
        }else{
            return json(['status' => 0, 'msg' => false]);
        }
    }
    
    /**
     * 消息搜索
     * @return \think\response\Json
     * key  搜索的关键字
     * page  列表页码
     */
    public function search(){
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == 112) {
            return json(['status' => 301, 'msg' => $this->otherLogin]);
        }elseif($res == 110){
            return json(['status' => 302, 'msg' => $this->frost]);
        }
        
        $page = input('page') ? input('page') : 1;
        $key = input('key') ? input('key') : '';
        $user_info = Db::table('up_u_user')->where('user_id', $params['user_id'])->find();
        $school_id_str = ',' . $user_info['user_school'] . ',';
        $qu_id_str = ',' . $user_info['user_qu'] . ',';
        $where['n_title'] = ['like', '%' . $key . '%'];
        $where['n_school'] = [['like', '%' . $school_id_str . '%'], ['like', '%' . $qu_id_str . '%'], 'or'];
        $where['n_status'] = 1;
        $where['n_del'] = 1;
        if(isset($params['old_1']) && $params['old_1'] == 1){ //特别照顾旧版本
            $where['n_type'] = 2;
        }
        $findLists = Db::table('up_notice')
            ->field('n_id, n_title, n_type, n_time, n_thumb, n_start_time, n_end_time, n_apply_start_time, 
            n_apply_end_time')
            ->where($where)
            ->page($page, 10)
            ->order('n_time desc')
            ->select();
        foreach ($findLists as $key=>&$vo){
            $vo['n_time'] = date('Y.m.d H:i:s',strtotime($vo['n_time']));
        }
        if($findLists){
            $findLists = $this->getFindLists($params['user_id'], $findLists);
            return json(['status' => 200, 'msg' => $findLists]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 组装列表展示的数组
     * @param $user_id
     * @param $findLists
     * @return mixed
     */
    public function getFindLists($user_id, $findLists){
        foreach($findLists as $key => $va){
            if($va['n_type'] == 1){//筛选出研学
                //已报名
                $apply = Db::table('up_studies')
                    ->where('st_n_id', $va['n_id'])
                    ->where('st_user_id', $user_id)
                    ->find();
                if($apply && $apply['st_pay_status'] == 2){//已缴费
                    $findLists[$key]['apply'] = 1;//已报名
                }else{
                    $findLists[$key]['apply'] = 0;//未报名
                }
                //报名中
                if(strtotime($va['n_apply_end_time']) >= time() && strtotime($va['n_apply_start_time']) <= time()){
                    $findLists[$key]['applying'] = 1;//报名中
                }else{
                    $findLists[$key]['applying'] = 0;
                }
                //已结束
                if(time() > strtotime($va['n_end_time'])){
                    $findLists[$key]['end'] = 1;//已结束
                }else{
                    $findLists[$key]['end'] = 0;
                }
            }
        }
        return $findLists;
    }

    //删除报名研学活动
    public function delNotice(){
        $id = input('param.id');
        $res = Db::table('up_notice_order')->where('notice_id',$id)->find();
        Db::table('up_studies')->where('st_id',$res['studies_id'])->delete();
        $res2 = Db::table('up_notice_order')->where('notice_id',$id)->delete();
    }

    public function studies(){
        $id = input('param.id');
        $res = Db::table('up_studies')->where('st_id',$id)->find();
        return json(['status' => 200, 'msg' => $res]);
    }

    public function updateStudies(){
        $params = input('param.');
        $id = input('param.id');
        $data['st_user_name'] = $params['st_user_name'];
        $data['st_user_code'] = $params['st_user_code'];
        $data['st_user_phone'] = $params['st_user_phone'];
        $data['st_urg_name'] = $params['st_urg_name'];
        Db::table('up_studies')->where('st_id',$id)->update($data);
        return json(['status' => 200, 'msg' => '']);
    }
}